import 'package:flutter/cupertino.dart';
import 'package:flutter/material.dart';
import 'package:flutter_app/components/layout.dart';
import 'package:flutter_app/utils/AppUtil.dart';
import 'package:flutter_app/components/Expansion.dart';

class LoanDetailPage extends StatefulWidget {
  @override
  _LoanDetailPageState createState() => _LoanDetailPageState();
}

Widget DialogText(String text) {
  return Text(text,
      style: TextStyle(
          color: Colors.black, fontWeight: FontWeight.w500, height: 1.7));
}

void showReplenishmentDialog(context) {
  AppUtil.showSimpleDialog(context, children: [
    Container(
        padding: EdgeInsets.symmetric(horizontal: 20.0, vertical: 20.0),
        child: DialogText(
          '开启本功能即同意：每当质押物价触及预警线时，平台将自动从您的余额账户扣款，作为质押物转移至质押账户，使当前质押率降低至初始质押率。请保持资产账户余额充足以便自动扣款。',
        )),
    TextButton(
        onPressed: () {
          Navigator.pop(context);
        },
        child: Text('我知道了'))
  ]);
}

void showPledgeDialog(context) {
  AppUtil.showSimpleDialog(context, children: [
    Container(
        padding: EdgeInsets.symmetric(horizontal: 20.0, vertical: 20.0),
        child: Column(
          children: [
            DialogText(
              '质押率',
            ),
            DialogText('质押率=借款资产价值/质押资产价值，质押率越高，借款订单风险也越高。'),
            DialogText('例如，假设1BTC=11,000USDT,60%质押率 1BTC可以借出6,600.00 USDT')
          ],
        )),
    TextButton(
        onPressed: () {
          Navigator.pop(context);
        },
        child: Text('我知道了'))
  ]);
}

Widget LeftText(String text, {Widget right}) {
  return Row(
    children: [
      Text(
        text,
        style: TextStyle(fontSize: 15, fontWeight: FontWeight.w500),
      ),
      right ?? Text('')
    ],
  );
}

Widget showLimit(context) {}
Widget NewExpansion(context, {String title, Widget child, bool active}) {
  return Container(
    padding: EdgeInsets.symmetric(vertical: 10.0),
    decoration: BoxDecoration(
        border: Border(
            top: BorderSide(
      color: Colors.grey.withOpacity(0.3),
    ))),
    child: Expansion(
        active: active,
        title: title,
        titleStyle: TextStyle(
            fontSize: 15, fontWeight: FontWeight.w500, color: Colors.black),
        child: Container(
            width: MediaQuery.of(context).size.width - 30, child: child)),
  );
}

Widget TryItem({String left, String right}) {
  return RowBetween(children: [
    Text(left, style: TextStyle(fontWeight: FontWeight.w500,color: Colors.black54)),
    Text(right, style: TextStyle(fontWeight: FontWeight.w600,fontFamily: 'dinpro',color: Colors.black)),
  ]);
}

Widget showRule(context) {
  GetBottomSheet(context, text: 'BCH/BTC 30 天规则介绍', children: [
    Container(
        padding: EdgeInsets.only(right: 15.0),
        child: Wrap(
          children: [
            NewExpansion(context,
                active: true,
                title: '补仓规则',
                child: Text(
                    '您可开启自动补仓功能或在放款后手动补仓，并请关注预警时的短信或邮件通知及"我的订单"页面的预警标识。质押数币价格下跌情况下，质押率高于60%时，需及时补充质押物。'
                    '质押率=(借款金额+借款利息+罚息总额-已还金额)/质押数币估值*100%')),
            NewExpansion(context,
                title: '平仓规则',
                child: Text(
                    '下列情况可能会被强制平仓1.质押数币价格下跌情况下，质押率高于75%，质押物价值小于10 BTC时，将被强制平仓。2.逾期超过0天时，将被强制平仓。平仓发生时将计提风险准备金(风险准备金=应还本息(罚息) x1%)，由平仓所得支付。当质押率高于75%，质押物价值大于等于10 BTC时，将卖出部分质押物以使质押率下降到预警线60%。应卖质押物= (借款金额-质押物价值*预警线)/(1-预警线),借款金额将转换成质押币种计算。')),
            NewExpansion(context,
                title: '计息规则',
                child: Text('该产品年化利率0.0191%,按日计息。提前还款不减免应收利息，按到期应还计算应还本息')),
            NewExpansion(context,
                title: '还款规则',
                child: Text(
                    '还款时，请在钱包余额账户充值足额的应还款项，可提前主动还款或等待到期扣款。结清应还金额后，系统将自动解质押，质押物到账以实际到账时间为准。还款时，您能选择把质押物市价卖出还款。还款时，您能自定义还款金额进行部分还款，系统还款顺序是罚息、利息、本金。')),
            NewExpansion(context,
                title: '罚息规则',
                child: Text('超过应还日期未还款的，将按照日利率0.0547%x借款本息x逾期天数计收罚息。')),
            NewExpansion(context,
                title: '续借规则',
                child: Text(
                    '续借是用户按照借款订单价格申请新- -个周期的借款，得到投资方同意后生效，包括三个步骤:1、续借申请:可在借款时开启自动续借，也可在订单操作里申请续借，发起申请时需要冻结续借所需费用(包括续借期间利息和服务费) ; 2、续借审批:申请发起后，投资方有权视自身情况同意或拒绝，最长审批时长是24小时; 3、续借生.效:订单到期时，如果未发生平仓，则订单终结并生成续借订单，续借费用扣收，之后您只需按照续借订单的到期时间归还本息后退还质押物。')),
            NewExpansion(context,
                title: '风险提示',
                child: Text(
                    '1.若借款存续期间，针对借款标的的法律或监管政策导致借款人无法使用BCH履行借款到期返还义务、或出现BCH与美金参考汇率较借款日发生大幅价值波动以及其他不可抗力情形，平台有权要求借款人以法币或者其他数字货币的形式履行借款到期返还义务。2.平台有权利在市场大幅波动^下对平仓规则进行调整，包括但不仅限于调整分级平仓阈值、择时出售全部质押物等。平台出售质押物后仍存在损失的，有权针对该等损失对乙方进行追偿.')),
          ],
        )),
  ]);
}

class _LoanDetailPageState extends State<LoanDetailPage> {
  bool replenishment = false;
  bool isAgree = false;
  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: DarkHeadBar('', actions: [
        TextButton(
            onPressed: () {},
            child: Text(
              '指数 106.88621',
              style: TextStyle(fontFamily: 'dinpro', color: Colors.black),
            ))
      ]),
      body: ColumnStart(
        children: [
          Expanded(
              child: SingleChildScrollView(
            child: Container(
              padding: EdgeInsets.symmetric(horizontal: 20.0),
              child: ColumnStart(
                children: [
                  Row(
                    children: [
                      Text(
                        'BCH 7-30天',
                        style: TextStyle(
                            color: Colors.black,
                            fontWeight: FontWeight.w500,
                            fontSize: 16,
                            fontFamily: 'dinpro'),
                      ),
                      Text(
                        ' 5.986%',
                        style: TextStyle(
                            color: Colors.orangeAccent,
                            fontWeight: FontWeight.w600,
                            fontSize: 18,
                            fontFamily: 'dinpro'),
                      )
                    ],
                  ),
                  Stack(
                    children: [
                      TextField(
                        decoration: InputDecoration(
                          hintText: "借款金额：1~" + AppUtil.formatNum(50000000),
                          hintStyle:
                              TextStyle(color: Colors.grey, fontSize: 15),
                          contentPadding: EdgeInsets.only(right: 100),
                          enabledBorder: UnderlineInputBorder(
                              borderSide: BorderSide(
                                  color: Colors.grey.withOpacity(0.4),
                                  width: 0.5)),
                        ),
                      ),
                      Positioned(
                          right: 0,
                          bottom: 10,
                          child: Row(
                            children: [
                              VerticalDivideLine(),
                              SizedBox(width: 16),
                              Row(children: [
                                Image.asset(
                                  'assets/images/ic_btc.png',
                                  width: 25,
                                  height: 25,
                                ),
                                SizedBox(width: 6.0),
                                Text('BTC',
                                    style: TextStyle(
                                        fontWeight: FontWeight.w600,
                                        fontSize: 16)),
                              ])
                            ],
                          ))
                    ],
                  ),
                  SizedBox(
                    height: 15.0,
                  ),
                  Stack(
                    children: [
                      TextField(
                        decoration: InputDecoration(
                          hintText: "质押金额：0.00",
                          enabledBorder: UnderlineInputBorder(
                              borderSide: BorderSide(
                                  color: Colors.grey.withOpacity(0.4),
                                  width: 0.5)),
                          hintStyle:
                              TextStyle(color: Colors.grey, fontSize: 15),
                          contentPadding: EdgeInsets.only(right: 100),
                        ),
                      ),
                      Positioned(
                          right: 0,
                          bottom: 10,
                          child: Row(
                            children: [
                              VerticalDivideLine(),
                              SizedBox(width: 16),
                              Row(children: [
                                Image.asset(
                                  'assets/images/ic_btc.png',
                                  width: 25,
                                  height: 25,
                                ),
                                SizedBox(width: 6.0),
                                Text('BTC',
                                    style: TextStyle(
                                        fontWeight: FontWeight.w600,
                                        fontSize: 16)),
                              ])
                            ],
                          ))
                    ],
                  ),
                  Row(
                    children: [
                      Text(
                        '可用余额：0.00BTC',
                        style: TextStyle(
                            fontFamily: 'dinpro', color: Colors.black54),
                      ),
                      TextButton(
                          onPressed: () {
                            Navigator.pushNamed(context, '/trade/charge');
                          },
                          child: Text('充值'))
                    ],
                  ),
                  Wrap(
                    runSpacing: 25.0,
                    children: [
                      RowBetween(children: [
                        LeftText('自动补仓 ',
                            right: GestureDetector(
                                onTap: () {
                                  showReplenishmentDialog(context);
                                },
                                child: Icon(
                                  Icons.info_outline,
                                  size: 18,
                                  color: Colors.grey,
                                ))),
                        SizedBox(
                          height: 25,
                          child: Switch(
                              value: replenishment,
                              onChanged: (value) {
                                replenishment = value;
                                setState(() {
                                  replenishment = value;
                                });
                              }),
                        )
                      ]),
                      RowBetween(children: [
                        LeftText('质押率 ',
                            right: GestureDetector(
                                onTap: () {
                                  showPledgeDialog(context);
                                },
                                child: Icon(
                                  Icons.info_outline,
                                  size: 18,
                                  color: Colors.grey,
                                ))),
                        LeftText('50%')
                      ]),
                      InkWell(
                        onTap: () {
                          showLimit(context);
                        },
                        child: RowBetween(children: [
                          LeftText('期限'),
                          Row(
                            children: [
                              LeftText('30天 '),
                              Icon(
                                Icons.arrow_forward_ios_outlined,
                                size: 14,
                              )
                            ],
                          )
                        ]),
                      ),
                      InkWell(
                        onTap: () {
                          showRule(context);
                        },
                        child: RowBetween(children: [
                          LeftText('产品规则'),
                          Icon(
                            Icons.arrow_forward_ios_outlined,
                            size: 14,
                          )
                        ]),
                      ),
                      Expansion(
                        title: '借款试算',
                        titleStyle: TextStyle(
                            fontSize: 15, fontWeight: FontWeight.w500),
                        child: Container(
                          width: MediaQuery.of(context).size.width - 40,
                          padding: EdgeInsets.all(10.0),
                          decoration: BoxDecoration(
                              color: Colors.grey.withOpacity(0.1),
                              borderRadius: BorderRadius.circular(6.0)),
                          child: Wrap(
                            runSpacing: 15.0,
                            children: [
                              TryItem(left: '借款本金', right: '0.00 BCH'),
                              TryItem(left: '借款利息', right: '0.00 BCH'),
                              TryItem(left: '到账金额', right: '0.00 BCH'),
                              TryItem(left: '到期时间', right: '--'),
                              TryItem(left: '到期应还', right: '0.00 BCH'),
                              TryItem(left: '还款方式', right: '--'),
                              TryItem(left: '预警线', right: '--'),
                              TryItem(left: '平仓线', right: '--'),
                            ],
                          ),
                        ),
                      ),
                      TextField(
                        decoration: InputDecoration(
                          hintText: "邀请码（选填）",
                          filled: true,
                          hintStyle:
                              TextStyle(color: Colors.grey, fontSize: 15),
                          contentPadding: EdgeInsets.symmetric(
                              vertical: 15.0, horizontal: 15.0),
                          border:
                              OutlineInputBorder(borderSide: BorderSide.none),
                        ),
                      )
                    ],
                  ),
                ],
              ),
            ),
          )),
          Container(
            padding: EdgeInsets.symmetric(vertical: 15.0, horizontal: 20.0),
            child: Column(
              children: [
                Row(
                  children: [
                    SizedBox(
                      height: 24.0,
                      width: 24.0,
                      child: Checkbox(
                        value: isAgree,
                        onChanged: (bool value) {
                          setState(() {
                            this.isAgree = value;
                          });
                        },
                      ),
                    ),
                    Text('承诺借款用于'),
                    TextButton(onPressed: () {}, child: Text('日常消费')),
                    Text(', 并同意'),
                    TextButton(onPressed: () {}, child: Text('《借款协议》'))
                  ],
                ),
                FlatButton(
                    onPressed: () {},
                    minWidth: double.infinity,
                    height: 40,
                    shape: RoundedRectangleBorder(
                        borderRadius: BorderRadius.all(Radius.circular(5))),
                    color: Colors.blueAccent,
                    textColor: Colors.white,
                    child: Text('提交申请'))
              ],
            ),
          )
        ],
      ),
    );
  }
}
